//
//  ConvenientTool.m
//  中邮阅读2
//
//  Created by yuzhou on 13-10-11.
//  Copyright (c) 2013年 Changxy. All rights reserved.
//

#import "ConvenientTool.h"
#import "AppDelegate.h"

ConvenientTool * convenientTool = nil;
@implementation ConvenientTool
+ (ConvenientTool *)sharedConvenienTool{
    if (!convenientTool) {
        convenientTool = [[ConvenientTool alloc]init];
    }
    return convenientTool;
}


+ (CGRect)fitSizeForSize:(CGSize)inSize inSize:(CGSize)outSize
{
    CGSize finalSize = CGSizeZero;

    if (inSize.width / inSize.height < outSize.width / outSize.height) {
        finalSize.height = outSize.height;
        finalSize.width = outSize.height / inSize.height * inSize.width;
    }
    else {
        finalSize.width = outSize.width;
        finalSize.height = outSize.width / inSize.width * inSize.height;
    }
    
    return CGRectMake(0, 0, finalSize.width, finalSize.height);
}
//检测更新 苹果服务器
- (BOOL)haveNewUpdate{
    NSDictionary *infoDict = [[NSBundle mainBundle]infoDictionary];
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];
    id obj = [[DataRequest sharedRequest] detectionUpdate];
    NSLog(@"obj:%@",obj);
    NSString * appVersion = nil;
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary * dict = [[obj objectForKey:@"results"] lastObject];
        appVersion = [dict objectForKey:@"version"];
    }
    if (![currentVersion isEqualToString:appVersion] && appVersion != nil) {
        return YES;
    }
    return NO;
}

//检测更新 公司服务器
-(void)ChackAppVersionNeedPopAlert:(BOOL)pop{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest]getAppVersionInfo];
        NSLog(@"版本信息:%@",obj);
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter ] postNotificationName:@"cannotpushtheButton" object:nil userInfo:nil];
            //从info.plist文件中读取当前的版本信息
            NSDictionary *infoDict = [[NSBundle mainBundle]infoDictionary];
            NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];
            NSLog(@"currentVersion:%@",currentVersion);
            NSString *appVersion = nil;
            if ([obj isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dict = [obj objectForKey:@"result"];
                appVersion = [[dict objectForKey:@"version_num"] stringValue];
                NSLog(@"appVersion:%@",appVersion);
                //                if ([appVersion compare:currentVersion] != NSOrderedSame) {
                if ([appVersion floatValue] > [currentVersion floatValue]) {
                    
                    
                    //判断是否要强制升级
                    self.isCompel = [[dict objectForKey:@"is_compel"] boolValue];
                    if (self.isCompel) {
                        
                        
                        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"有新版本更新" delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"升级", nil];
                        alertView.tag = 1;
                        [alertView show];
                    }
                    else{
                        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"有新版本更新" delegate:self cancelButtonTitle:@"稍后升级" otherButtonTitles:@"升级", nil];
                        alertView.tag = 2;
                        [alertView show];
                    }
                }else{
                    //是否需要弹出已是最新版本的提示
                    if (pop) {
                        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"当前已是最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [alertView show];
                    }
                    
                }
            }
            
        });
        
    });

}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //强制升级
    if (alertView.tag == 1) {
        switch (buttonIndex) {
            case 0:
            {
                exit(0);
            }
                break;
            case 1:
            {
                NSLog(@"升级");
                
                [self showAppInfo];
            }
                break;
                
            default:
                break;
        }
    }
    //不需要强制升级
    else{
        switch (buttonIndex) {
            case 0:
            {
                //稍后升级
            }
                break;
            case 1:
            {
                NSLog(@"升级");
                [self showAppInfo];
            }
                break;
                
            default:
                break;
        }
    }
}





- (void)showAppInfo{
    //6.0之前之只能推到AppStore，6.0之后可以在本程序里添加
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 6.0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@",ITUNES_APP_KEY]]];
    }else{
        [self evaluate];
    }
}


- (void)evaluate{
    //初始化控制器
    SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
    //设置代理请求为当前控制器本身
    storeProductViewContorller.delegate = self;
    
    AppDelegate *deldgate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    
    [deldgate.viewController presentViewController:storeProductViewContorller animated:YES completion:^{
        //加载一个新的视图展示
        [storeProductViewContorller loadProductWithParameters:
         //appId唯一的
         @{SKStoreProductParameterITunesItemIdentifier : ITUNES_APP_KEY} completionBlock:^(BOOL result, NSError *error) {
             //block回调
             if(error){
                 NSLog(@"error %@ with userInfo %@",error,[error userInfo]);
             }else{
                 //模态弹出appstore
                 
             }
         }];
    }
     ];
    
}
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
    AppDelegate *deldgate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    [deldgate.viewController dismissViewControllerAnimated:YES completion:^{
        //当在AppStore中点击返回没更新程序退出
        if (self.isCompel) {
            exit(0);
        }

    }];
}

@end
